//
//  LoginViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/21.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SwiftyJSON
import SVProgressHUD

protocol  LoginViewControllerDelegate{
    func letRightVCRefresh()
}

class LoginViewController: UIViewController {

//声明代理
    var delegate : LoginViewControllerDelegate?
    
    
    
    var allPrice : String?
    var cartArray : NSMutableArray?
    var dic : NSDictionary?
    var isShoppingCar : Bool?
    
    
    
    
    
//    上方的登录注册按钮
    var registerBtn = UIButton(type: .custom)
    var loginBtn = UIButton(type: .custom)
    
    var registerView = UIView()
    var loginView = UIView()
    
    var loginTextField1 = UITextField()
    var loginTextField2 = UITextField()
    
    var registerTextField1 = UITextField()
    var registerTextFirld2 = UITextField()
    var registerTextField3 = UITextField()
    
//    下面 view 上面的 登录创建按钮
    var creatButton = UIButton(type: .custom)
    var logButton = UIButton(type: .custom)
    
    
    
    
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor.white
        
        self.creatNavVIew()
        self.creatView()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

extension LoginViewController{
    
    fileprivate func creatNavVIew(){
        
        self.navigationController?.navigationBar.barTintColor = UIColor(red: 94/255.0, green: 200/255.0, blue: 252/255.0, alpha: 1)
        
        let titleButton = UIButton(type: .custom)
        titleButton.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH*0.6, height: 64)
        titleButton.setTitle("LOG IN/CREATE ACCOUNT", for: UIControlState())
        titleButton.titleLabel?.textColor = UIColor.black
        let leftBarButtonItem = UIBarButtonItem(customView: titleButton)
        self.navigationItem.leftBarButtonItem = leftBarButtonItem
        
        
        let rightBtn = UIButton(type: .custom)
        rightBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        rightBtn.setImage(UIImage(named: "nav_close"), for: UIControlState())
        rightBtn.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
        let rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
        
    }
    
    
    func rightBtnClick(){
        
        if self.isShoppingCar == false || self.isShoppingCar == nil {
            self.dismiss(animated: true) {
                
            }
        }else{
            self.navigationController?.popViewController(animated: true)
        }
        
    }
    
    
}


extension LoginViewController{
    fileprivate func creatView(){
        
        
        loginBtn.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.06+64, width: SCREEN_WIDTH/2-20, height: SCREEN_HEIGHT*0.08)
        loginBtn.setImage(UIImage(named: "btn_login_n"), for: .selected)
        loginBtn.setImage(UIImage(named: "btn_login_s"), for: UIControlState())
        loginBtn.addTarget(self, action: #selector(loginBtnClick(_:)), for: .touchUpInside)
        loginBtn.isSelected = true
        self.view.addSubview(loginBtn)
        
        
        registerBtn.frame = CGRect(x: SCREEN_WIDTH/2, y: SCREEN_HEIGHT*0.06+64, width: SCREEN_WIDTH/2-20, height: SCREEN_HEIGHT*0.08)
        registerBtn.setImage(UIImage(named: "btn_register_n"), for: .selected)
        registerBtn.setImage(UIImage(named: "btn_register_s"), for: UIControlState())
        registerBtn.addTarget(self, action: #selector(registerBtnClick(_:)), for: .touchUpInside)
        self.view.addSubview(registerBtn)
        
//        创建登录视图
        loginView.frame = CGRect(x: 20, y: 64 + SCREEN_HEIGHT * 0.17, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.28)
        self.view.addSubview(loginView)
        
        let loginView1 = UIView()
        loginView1.backgroundColor = UIColor.white
        loginView1.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.08)
        loginView1.layer.borderColor = UIColor.gray.cgColor
        loginView1.layer.borderWidth = 2
        loginView.addSubview(loginView1)
        
        loginTextField1.frame = CGRect(x: 10, y: 5, width: SCREEN_WIDTH-60, height: SCREEN_HEIGHT*0.08-10)
        loginTextField1.placeholder = "E-MAIL＊"
        loginView1.addSubview(loginTextField1)
        
        
        let loginView2 = UIView()
        loginView2.backgroundColor = UIColor.white
        loginView2.frame = CGRect(x: 0, y: SCREEN_HEIGHT * 0.1, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT*0.08)
        loginView2.layer.borderColor = UIColor.gray.cgColor
        loginView2.layer.borderWidth = 2
        loginView.addSubview(loginView2)
        
        loginTextField2.frame = CGRect(x: 10, y: 5, width: SCREEN_WIDTH - 60, height: SCREEN_HEIGHT*0.08-10)
        loginTextField2.isSecureTextEntry = true
        loginTextField2.placeholder = "PASSWORD＊"
        loginView2.addSubview(loginTextField2)
        
        logButton.frame = CGRect(x: 0, y: SCREEN_HEIGHT * 0.2, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT*0.08)
        logButton.setTitle("LOGIN", for: UIControlState())
        logButton.setTitleColor(UIColor.white, for: UIControlState())
        logButton.backgroundColor = UIColor.black
        logButton.addTarget(self, action: #selector(logButtonCLick(_:)), for: .touchUpInside)
        loginView.addSubview(logButton)
        
        
//        创建注册视图
        registerView.frame = CGRect(x: 20, y: 64 + SCREEN_HEIGHT * 0.17, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.38)
        self.view.addSubview(registerView)
        
        let registerView1 = UIView()
        registerView1.backgroundColor = UIColor.white
        registerView1.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.08)
        registerView1.layer.borderColor = UIColor.gray.cgColor
        registerView1.layer.borderWidth = 2
        registerView.addSubview(registerView1)
        
        registerTextField1.frame = CGRect(x: 10, y: 5, width: SCREEN_WIDTH-60, height: SCREEN_HEIGHT*0.08-10)
        registerTextField1.placeholder = "E-MAIL＊"
        registerView1.addSubview(registerTextField1)
        
        
        let registerView2 = UIView()
        registerView2.backgroundColor = UIColor.white
        registerView2.frame = CGRect(x: 0, y: SCREEN_HEIGHT * 0.1, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT*0.08)
        registerView2.layer.borderColor = UIColor.gray.cgColor
        registerView2.layer.borderWidth = 2
        registerView.addSubview(registerView2)
        
        registerTextFirld2.frame = CGRect(x: 10, y: 5, width: SCREEN_WIDTH - 60, height: SCREEN_HEIGHT*0.08-10)
        registerTextFirld2.isSecureTextEntry = true
        registerTextFirld2.placeholder = "PASSWORD＊"
        registerView2.addSubview(registerTextFirld2)
        
        
        let registerView3 = UIView()
        registerView3.backgroundColor = UIColor.white
        registerView3.frame = CGRect(x: 0, y: SCREEN_HEIGHT * 0.2, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT*0.08)
        registerView3.layer.borderColor = UIColor.gray.cgColor
        registerView3.layer.borderWidth = 2
        registerView.addSubview(registerView3)
        
        registerTextField3.frame = CGRect(x: 10, y: 5, width: SCREEN_WIDTH - 60, height: SCREEN_HEIGHT*0.08-10)
        registerTextField3.isSecureTextEntry = true
        registerTextField3.placeholder = "VERIFY PASSWORD＊"
        registerView3.addSubview(registerTextField3)
        
        creatButton.frame = CGRect(x: 0, y: SCREEN_HEIGHT * 0.3, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT*0.08)
        creatButton.setTitle("CREATE ACCOUNT", for: UIControlState())
        creatButton.setTitleColor(UIColor.white, for: UIControlState())
        creatButton.backgroundColor = UIColor.black
        creatButton.addTarget(self, action: #selector(creatButtonCLick(_:)), for: .touchUpInside)
        registerView.addSubview(creatButton)
        
        
//        创建facebook视图
        let facebookImageView = UIImageView()
        facebookImageView.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.55+64, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.04)
        facebookImageView.image = UIImage(named: "fenge")
        self.view.addSubview(facebookImageView)
        
        let facebookBtn = UIButton(type: .custom)
        facebookBtn.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.6+64, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.08)
        facebookBtn.setImage(UIImage(named: "face-book"), for: UIControlState())
        facebookBtn.addTarget(self, action: #selector(facebookBtnCLick), for: .touchUpInside)
        self.view.addSubview(facebookBtn)
        
        
        
        
        loginView.isHidden = false
        registerView.isHidden = true
        
    }
//    facebook按钮点击方法
    func facebookBtnCLick(){
        
    }
    
//    上面的登录注册方法
    func loginBtnClick(_ button : UIButton){
        
        loginBtn.isSelected = true
        registerBtn.isSelected = false
        
        loginView.isHidden = false
        registerView.isHidden = true
    }
    
    func registerBtnClick(_ button : UIButton){
        loginBtn.isSelected = false
        registerBtn.isSelected = true
        
        loginView.isHidden = true
        registerView.isHidden = false
    }
    
//    下面的 view上的 登录创建方法
    func logButtonCLick(_ button:UIButton){
        self.goToLogin()
            }
    
    func creatButtonCLick(_ button:UIButton){
        let urlStr = APIBASE + "main_page=create_account"
        let parma=["email_address":self.registerTextField1.text!,"telephone":"**********","password":self.registerTextFirld2.text!,"confirmation":self.registerTextField3.text!]
        NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
                
                let status = Int(((result as? NSDictionary)!["status"]as?NSNumber)!)
                if status == 1{
                    SVProgressHUD.showSuccess(withStatus: (result as? NSDictionary)!["status_message"]as?String)
                    self.nextToLogin()
                }else{
                    let message = (result as? NSDictionary)!["status_message"]as?String
                    SVProgressHUD .showError(withStatus: message)
                }
            }else{
                SVProgressHUD.show(withStatus: "register error:"+String(describing: error))
                print("register error:"+String(describing: error))
            }
        }
        
        
    }
    func nextToLogin(){
        self.loginTextField1.text = self.registerTextField1.text!
        self.loginTextField2.text = self.registerTextFirld2.text!
        self.goToLogin()
    }
    
    
    func goToLogin(){
        if self.loginTextField1.text == nil || self.loginTextField2.text == nil {
            SVProgressHUD.show(withStatus: "Please complete the login information!")
        }else{
            let urlStr = APIBASE + "main_page=login"
            let parma = ["email_address":self.loginTextField1.text!,"password":self.loginTextField2.text!]
            
            NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as [String : NSObject], finishedBlock: { (result, error) in
                if result != nil{
                    //                    let json = JSON(result!)
                    //                    print(json)
                    
                    let status = Int(((result as? NSDictionary)!["status"]as?NSNumber)!)
                    if status == 1{
                        SVProgressHUD.showSuccess(withStatus: (result as? NSDictionary)!["status_message"]as?String)
                        
                        self.getCookie()
                        
                        UserSession.shareInstance.email = self.loginTextField1.text!
                        UserSession.shareInstance.isLogin = true
                        if self.isShoppingCar == false || self.isShoppingCar == nil{
                            self.goToRightVC()
                        }else{
                            self.goToProcessOrderVC()
                        }
                        
                    }else{
                        let message = (result as? NSDictionary)!["status_message"]as?String
                        SVProgressHUD .showError(withStatus: message)
                    }
                    
                }else{
                    SVProgressHUD.show(withStatus: "register error:"+String(describing: error))
                    print("register error:"+String(describing: error))
                }
            })
            
            
        }

    }
    
    func goToRightVC(){
        self.dismiss(animated: true) { 
            self.delegate?.letRightVCRefresh()
        }
        
//        登录之后让主页和右侧页面刷新
        let center = NotificationCenter.default
        let notification = Notification(name: Notification.Name(rawValue: "LoginMakeMainVCRefresh"), object: self, userInfo: nil)
        center.post(notification)
        
        
        
    }
    func goToProcessOrderVC(){
        let processVC = ProcessOrderViewController()
        processVC.dic = self.dic
        processVC.allPrice = self.allPrice
        processVC.cartArray = self.cartArray
        self.isShoppingCar = false
        self.navigationController?.pushViewController(processVC, animated: true)
        
        let center = NotificationCenter.default
        let notification = Notification(name: Notification.Name(rawValue: "LoginMakeMainVCRefresh"), object: self, userInfo: nil)
        center.post(notification)
        
        let center1 = NotificationCenter.default
        let notification1 = Notification(name: Notification.Name(rawValue: "RightVCRefreshed"), object: self, userInfo: nil)
        center1.post(notification1)
    }
    
    func getCookie(){
        let parma = ["main_page":"zenid"]
        
        NetworkTool.shareInstance.request(.get, urlString: APIBASE, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
//                                print(result)
                
                let dic = result as? NSDictionary
                
                let zenid = (dic!["data"]as?NSDictionary)!["zenid"]as?String
                UserSession.shareInstance.cookie = zenid!
                print(UserSession.shareInstance.cookie!)
                
            }else{
                SVProgressHUD.showError(withStatus: "Get cookie error" + String(describing: error))
                print("Get cookie error" + String(describing: error))
            }
        }

    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    
}














